package cn.itcast.user.web;

import cn.itcast.user.common.ResponseResult;
import cn.itcast.user.common.ResultCode;
import cn.itcast.user.param.user.UserLoginParam;
import cn.itcast.user.param.user.UserRegisterParam;
import cn.itcast.user.pojo.User;
import cn.itcast.user.service.UserService;
import cn.itcast.user.util.JwtUtil;
import cn.itcast.user.vo.UserVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import static cn.itcast.user.common.ApiConstants.TOKEN_KEY;
import static cn.itcast.user.common.ApiConstants.USER_PREFIX;

@Slf4j
@RestController
@RequestMapping(USER_PREFIX)
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * token有效时间
     */
    @SuppressWarnings("FieldCanBeLocal")
    private final int KEEP_TIME = 60 * 1000 * 30;

    /**
     * 路径： /user/110
     *
     * @param id 用户id
     * @return 用户
     */
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id) {
        return userService.getById(id);
    }

    /**
     * 用户注册
     *
     * @param user 前端填写的用户信息
     * @return 注册结果
     */
    @ApiOperation(value = "用户注册")
    @PostMapping("userRegister")
    public ResponseResult userRegister(
            @RequestBody
            @Validated
            UserRegisterParam user
    ) {
        Boolean addResult = userService.addUser(user);
        if (addResult) {
            return new ResponseResult(ResultCode.SUCCESS.getCode(), "注册成功", addResult);
        }
        return new ResponseResult(ResultCode.FAILURE.getCode(), "注册失败", addResult);
    }

    /**
     * 用户登录
     *
     * @param user 登录信息
     * @return 登录结果
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("userLogin")
    public ResponseResult userLogin(@RequestBody UserLoginParam user, HttpServletResponse response) {
        User result = userService.doUserLogin(user.getAccount(), user.getPassword());
        if (result == null) {
            return new ResponseResult(ResultCode.FAILURE.getCode(), "登录失败", null);
        }

        String userId = result.getId().toString();
        String token = JwtUtil.generateToken(userId, KEEP_TIME);
        // 登录成功 生成并返回token cookie
        response.addCookie(new Cookie(TOKEN_KEY, token));

        // des target
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(result, userVO);
//        UserVO re = new UserVO(result.getAccount(), result.getUsername(), result.getAddress());
        return new ResponseResult(ResultCode.SUCCESS.getCode(), "登录成功", userVO);
    }
}
